<%@ page import="com.cy.model.Menu" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="menuTypes" value="<%= Menu.Type.toJson()%>"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="../styles/dpl-min.css" rel="stylesheet"/>
    <link href="../styles/bui-min.css" rel="stylesheet"/>
    <link href="../styles/main.css" rel="stylesheet"/>
</head>
<body>

<!--列表页-->
<div class="container">
    <form id="searchForm" class="form-panel">
        <ul class="panel-content">
            <li>
                <span>
                    <label>名称：</label><input type="text" class="control-text" name="accountRole.name" />
                </span>
                <span>
                    <label>状态：</label><input type="text" class="control-text" name="accountRole.status" />
                </span>
                <button type="button" id="btnSearch" class="button button-primary">搜索</button>
            </li>
        </ul>
    </form>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>
</div>

<!--表单页-->
<div id="ModelFormDialog" style="display: none">
    <form id="ModelForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">名称：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" data-rules="{required:true}" name="accountRole.name" data-rules="{required:true}"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">角色代码：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" data-rules="{required:true}" name="accountRole.code" data-rules="{required:true}"/>
            </div>
        </div>
        <div class="control-group" style="height: 130px;">
            <label class="control-label">备注：</label>
            <div class="controls">
                <textarea name="accountRole.remark" style="resize: none; width: 605px; height: 100px;"></textarea>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">状态：</label>
            <div class="controls">
                <select name="accountRole.status">
                    <option value="1">启用</option>
                    <option value="0">禁用</option>
                </select>
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>

<div id="userInfoDialog" style="display: none">
    <div class="search-grid-container">
        <div id="userInfoGrid"></div>
    </div>
</div>

<!--用户-->
<div id="UserInfoModelFormDialog" style="display: none">
    <form id="UserInfoModelForm" class="form-horizontal">
        <input type="text" name="accountMapRole.account_role_id" style="display: none;"/>
        <div class="control-group">
            <label class="control-label">用户名：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" data-rules="{required:true}" name="account" />
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3">
                <button type="submit" class="button button-primary">添加</button>
            </div>
        </div>
    </form>
</div>

<!-- 权限树 -->
<div id="permInfoDialog" style="display: none;">
    <div id="tab"></div>
    <div class="search-grid-container">
        <div id="permTree" style="height: 500px; overflow-y: auto;"></div>
        <shiro:hasPermission name="/clmp/accountRole/post_updatePerm:post">
            <div class="row form-actions actions-bar">
                <div class="text-center">
                    <button id="updatePermBtn" class="button button-primary">确定</button>
                        <%--<button id="allCheckedBtn" class="button button-primary">全选</button>--%>
                    <button id="allUncheckedBtn" class="button button-primary">全不选</button>
                    <button id="collapseBtn" class="button button-primary">折叠</button>
                    <button id="expandBtn" class="button button-primary">展开</button>
                </div>
            </div>
        </shiro:hasPermission>
    </div>
</div>

<script type="text/javascript" src="../scripts/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../scripts/bui.js"></script>
<script type="text/javascript" src="../scripts/treegrid-min.js"></script>
<script type="text/javascript" src="../scripts/common/search.js"></script>
<script type="text/javascript">
    var MENU_TYPES = ${menuTypes};
    var URI = "../clmp/accountRole", MODULE = 'accountRole';
    BUI.use(['common/search', 'bui/overlay', 'bui/form', 'bui/tree', 'bui/data', 'bui/tab'], function (Search, Overlay, Form, Tree, Data, Tab) {
        var columns = [
            {dataIndex: 'id', visible: false},
            {title: '名称', dataIndex: 'name', width: '10%'},
            {title: '角色代码', dataIndex: 'code', width: '10%'},
            {title: '创建日期', dataIndex: 'create_time', width: '10%'},
            {title: '备注', dataIndex: 'remark', width: '49%'},
            {title: '状态', dataIndex: 'status', width: '10%',renderer: function (value, obj) {
                switch (value){
                    case 0 : return "禁用";
                    case 1 : return "启用";
                    default : return null;
                }
            }},
          	{title: '操作', dataIndex: '', width: '8%', renderer: function (value, obj) {
                var editStr = '<shiro:hasPermission name="/clmp/accountRole/*:post"><span class="grid-command btn-edit" title="编辑">编辑</span></shiro:hasPermission>';
                var delStr = '<shiro:hasPermission name="/clmp/accountRole/*:delete"><span class="grid-command btn-del" title="删除">删除</span></shiro:hasPermission>';
                var userInfo = '<shiro:hasPermission name="/clmp/accountRole/getAccountByRole"><span class="grid-command btn-user" title="用户">用户</span></shiro:hasPermission>';
                var permInfo = '<shiro:hasPermission name="/clmp/accountRole/getPermTree"><span class="grid-command btn-perm" title="权限">权限</span></shiro:hasPermission>';
                return editStr + delStr + userInfo + permInfo;
        }}];
        var store = Search.createStore(URI, {totalProperty: 'total'});
        var gridCfg = Search.createGridCfg(columns, {
            tbar: {
                items: [
                    <shiro:hasPermission name="/clmp/accountRole:post">
                    {text: '<i class="icon-plus"></i>新建', btnCls: 'button button-small', handler: function () {
                        modelFormObject.clearFields();
                        modelFormObject.set('action', URI);
                        modelFormObject.set('method', "POST");
                        modelFormDialog.show();
                    }},
                    </shiro:hasPermission>
                    {
                        <shiro:hasPermission name="/clmp/accountRole/*:delete">
                        text: '<i class="icon-remove"></i>删除', btnCls: 'button button-small', handler: delFunction
                        </shiro:hasPermission>
                    }
                ]
            },
            emptyDataTpl : '<div style="padding: 20px" class="centered"><img src="../img/nodata.png"><h2>好像还没有数据</h2></div>',
            plugins: [BUI.Grid.Plugins.CheckSelection]
        });

        var search = new Search({
            store: store,
            gridCfg: gridCfg
        });
        var grid = search.get('grid');
        
        //删除操作
        function delFunction() {
            var selections = grid.getSelection();
            delItems(selections);
        }

        function delItems(items) {
            var ids = [];
            BUI.each(items, function (item) {
                ids.push(item.id);
            });

            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    $.ajax({
                        url: URI + "/" + ids.join("-"),
                        dataType: 'json',
                        type: 'DELETE',
                        data: {ids: ids},
                        success: function (data) {
                            if (data.status == 1) {
                                alert('操作成功');
                                search.load();
                            } else {
                                alert('删除失败！');
                            }
                        }
                    });
                }, 'question');
            }
        }

        //监听事件，删除一条记录
        grid.on('cellclick', function (ev) {
            var sender = $(ev.domTarget); //点击的Dom
            if (sender.hasClass('btn-del')) {
                delItems([ev.record]);
            } else if (sender.hasClass('btn-edit')) {
                edit(ev.record);
            } else if (sender.hasClass('btn-user')) {
                userInfo(ev.record);
            } else if (sender.hasClass('btn-perm')) {
                permInfo(ev.record);
            }
        });

        function edit(record) {
            modelFormObject.clearFields();
            modelFormObject.set('action', URI + "/" + record.id);
            modelFormObject.set('method', "POST");

            for (var name in record) {
                modelFormObject.setFieldValue(MODULE +'.'+ name, record[name]);
            }
            modelFormDialog.show();
        }

        var modelFormDialog = new Overlay.Dialog({
            title: '表单',
            width: 800,
            height: 600,
            mask: false,
            buttons: [],
            contentId: 'ModelFormDialog'
        });

        var modelFormObject = new Form.HForm({
            srcNode: '#ModelForm',
            submitType: 'ajax',
            callback: function (data) {
                if (data.status == 1) {
                    alert('操作成功');
                    modelFormDialog.close();
                    search.load();
                } else {
                    alert('操作失败:' + data.msg);
                }
            }
        }).render();

        /***********************************用户信息******************************/
        var userInfoGrid, userInfoSearch, userInfoStore, isInitialized = false;
        var USER_INFO_URI = "../clmp/accountMapRole", USER_INFO_MODULE = "accountMapRole";
        function userInfo(record){
            userInfoDialog.show();
            userInfoModelForm.setFieldValue(USER_INFO_MODULE+'.account_role_id', record.id);
            if (isInitialized){//数据表格是否已经初始化过
                userInfoStore.load({"roleId" : record.id});
                return;
            }
            var userInfoColumns = [
                {dataIndex: 'id', visible: false},
                {dataIndex: 'account_id', visible: false},
                {dataIndex: 'account_role_id', visible: false},
                {title: '账号', dataIndex: 'account', width: '10%'},
                {title: '姓名', dataIndex: 'name', width: '10%'},
                {title: '工号', dataIndex: 'job_no', width: '10%'},
                {title: '部门', dataIndex: 'department', width: '10%'},
                {title: '手机', dataIndex: 'mobile', width: '10%'},
                {title: '邮箱', dataIndex: 'email', width: '13%'},
                {title: '状态', dataIndex: 'status', width: '8%',renderer:function(value, obj){
                    switch (value){
                        case 0 : return '冻结';
                        case 1 : return '在职';
                        case 2 : return '离职';
                        default : return null;
                    }
                }},
                {title: '创建时间', dataIndex: 'create_time', width: '15%'},
                {title: '操作', dataIndex: '', width: '7%', renderer: function (value, obj) {
                    var delStr = '<shiro:hasPermission name="/clmp/accountMapRole/*:delete"><span class="grid-command btn-del" title="删除">删除</span></shiro:hasPermission>';
                    return delStr;
            }}];
            userInfoStore = Search.createStore("../clmp/accountRole/getAccountByRole", {
                params : {roleId : record.id},
                totalProperty : 'total'
            });
            var userInfoGridCfg = Search.createGridCfg(userInfoColumns, {tbar:{
                items : [
                    <shiro:hasPermission name="/clmp/accountMapRole:post">
                    {
                        text : '<i class="icon-plus"></i>添加',
                        btnCls : 'button button-small',
                        handler : function() {
                            userInfoModelForm.set('action',USER_INFO_URI);
                            userInfoModelForm.set('method',"POST");
                            userInfoModelFormDialog.show();
                        }
                    },
                    </shiro:hasPermission>
                    {
                    <shiro:hasPermission name="/clmp/accountMapRole/*:delete">
                    text : '<i class="icon-remove"></i>删除',
                    btnCls : 'button button-small',
                    handler : delUserInfoFunction
                    </shiro:hasPermission>
                }]},
                emptyDataTpl : '<div style="padding: 20px" class="centered"><img src="../img/nodata.png"><h2>好像还没有数据</h2></div>',
                plugins : [ BUI.Grid.Plugins.CheckSelection ]
            });
            userInfoSearch = new Search({
                store : userInfoStore,
                autoSearch : true,
                gridId : 'userInfoGrid',
                gridCfg : userInfoGridCfg
            });
            userInfoGrid = userInfoSearch.get('grid');
            userInfoGrid.on('cellclick', function (ev) {
                var sender = $(ev.domTarget); //点击的Dom
                if (sender.hasClass('btn-del')) {
                    delUserInfoItems([ev.record]);
                }
            });
            isInitialized = true;
        }

        //用户详情对话框
        var userInfoDialog = new Overlay.Dialog({
            title : '用户详情',
            width : 1200,
            height : 800,
            contentId : 'userInfoDialog',
            buttons: []
        });
        userInfoDialog.on('closed', function () {
            userInfoModelForm.clearFields();
        });

        //用户详情表单对话框
        var userInfoModelFormDialog = new Overlay.Dialog({
            title: '加入角色',
            width: 400,
            height: 250,
            mask: true,
            buttons: [],
            contentId: 'UserInfoModelFormDialog'
        });
        userInfoModelFormDialog.on('closed', function () {
            var value = userInfoModelForm.getFieldValue("accountMapRole.account_role_id");
            userInfoModelForm.clearFields();
            userInfoModelForm.setFieldValue("accountMapRole.account_role_id", value);
        });

        //用户详情表单
        var userInfoModelForm = new Form.HForm({
            srcNode: '#UserInfoModelForm',
            submitType: 'ajax',
            callback: function (data) {
                if (data.status == 1) {
                    userInfoModelFormDialog.close();
                    userInfoStore.load();
                } else {
                    alert('操作失败 ' + data.msg);
                }
            }
        }).render();

        function delUserInfoFunction() {
            var selections = userInfoGrid.getSelection();
            delUserInfoItems(selections);
        }

        //删除用户
        function delUserInfoItems(items) {
            var ids = [];
            BUI.each(items, function (item) {
                ids.push(item.id);
            });

            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    $.ajax({
                        url: USER_INFO_URI +"/"+ ids.join("-"),
                        dataType: 'json',
                        type: 'DELETE',
                        data: {ids: ids},
                        success: function (data) {
                            if (data.status == 1) {
                                alert('操作成功');
                                userInfoStore.load();
                            } else {
                                alert('操作失败 ' + data.msg);
                            }
                        }
                    });
                }, 'question');
            }
        }

        /***********************************权限信息******************************/
        var permStore = new Data.TreeStore({
            url : '../clmp/accountRole/getPermTree',
            isStore : false,
            autoLoad : false,
            autoSync : true
        });

        var selectedType = null;
        var tab = new Tab.TabPanel({
            render : '#tab',
            elCls : 'nav-tabs',
            autoRender: true,
            itemTpl : '<a href="javascript:void(0);">{text}</a>',
            children:MENU_TYPES.slice(0)
        });
        tab.on('selectedchange',function(ev) {
            selectedType = ev.item.get("type");
            permTree.clearAllChecked();
            permStore.load({roleId : tab.get("roleId"), type: selectedType});
        });

        var permTree = new Tree.TreeList({
            render : '#permTree',
            autoRender : true,
            store : permStore,
            checkType: 'all', //checkType:勾选模式，提供了4中，all,onlyLeaf,none,custom
            showLine : true,
            cascadeCheckd : true
        });

        //权限详情对话框
        var permInfoDialog = new Overlay.Dialog({
            title : '权限',
            width : 400,
            height : 700,
            contentId : 'permInfoDialog',
            buttons: []
        });
        permInfoDialog.on("closed", function(){
            permTree.clearAllChecked();
        });

        function permInfo(record){
            tab.clearSelection();
            tab.set("roleId", record.id);
            tab.setSelected(tab.getItemAt(0));
            permInfoDialog.show();
            permInfoDialog.set("record", record);
        }

        $("#updatePermBtn").click(function(){
            var checkedNodes = permTree.getCheckedNodes();
            var ids = '';
            BUI.each(checkedNodes,function(node, index){
                ids += node.path;
            });
            ids = delRepeat(ids.substring(1, ids.length).split(",")).join();
            var record = permInfoDialog.get("record");
            $.post("../clmp/accountRole/post_updatePerm", {roleId: record.id, ids: ids, type: selectedType}, function(data){
                if (data.status == 1){
                    alert("操作成功，需重登录应用更新");
                    permStore.load({roleId : record.id});
                } else {
                    alert("操作失败"+ data.msg);
                }
            });
        });

        $("#allUncheckedBtn").click(function(){
            permTree.clearAllChecked();
        });

        $("#collapseBtn").click(function(){
            permTree.collapseAll();
        });

        $("#expandBtn").click(function(){
            permTree.expandAll();
        });

        //去重复
        function delRepeat(arr) {
            var temp = {}, len = arr.length;
            for (var i = 0; i < len; i++) {
                var tmp = arr[i];
                if (!temp.hasOwnProperty(tmp)) {
                    temp[arr[i]] = "yes";
                }
            }

            len = 0;
            var tempArr = [];
            for (var i in temp) {
                tempArr[len++] = i;
            }
            return tempArr;
        }
    });
</script>
</body>
</html>